package kuzha.runtime;

import java.util.Map;

import kuzha.KuzhaObject;

public class AsPattern extends CasePattern {
	public final String name;
	public final CasePattern pat;
	
	public AsPattern(String name, CasePattern pat) {
		if (name == null || pat == null)
			throw new IllegalArgumentException();
		this.name = name;
		this.pat = pat;
	}
	
	@Override
	public boolean match(KuzhaObject value, Map<String, KuzhaObject> vars) {
		if (vars.containsKey(name)) {
			KuzhaObject v2 = vars.get(name);
			if (v2 != null) {
				return v2.equals(value) && pat.match(v2, vars);
			}
			else {
				return v2 == value && pat.match(v2, vars);
			}
		}
		else {
			if (pat.match(value, vars)) {
				vars.put(name, value);
				return true;
			}
			else {
				return false;
			}
		}
	}
	
	public static AsPattern valueOf(String name, CasePattern pat) {
		return new AsPattern(name, pat);
	}
}
